#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

#define SERVER_PORT 8888
// #define SERVER_IP "192.168.47.165"
// #define SERVER_IP "192.168.47.180"
#define SERVER_IP "8.138.248.21"

typedef struct
{
    int sockfd;              // 通信的套接字
    struct sockaddr_in addr; // 服务器地址
} server_info_t;

// 接收服务器返回的消息
void *get_message(void *arg)
{
    server_info_t *info = (server_info_t *)arg;
    char buf[1024] = {0};
    while (1)
    {
        recv(info->sockfd, buf, sizeof(buf), 0);
        printf("服务器消息: %s\n", buf);
        memset(buf, 0, sizeof(buf));
    }
}

void *send_message(void *arg)
{
    server_info_t *info = (server_info_t *)arg;
    while (1)
    {
        // 连接到服务器
        if (connect(info->sockfd, (struct sockaddr *)&info->addr, sizeof(info->addr)) < 0)
        {
            perror("connect error");
            continue;
        }

        printf("Connected to server successfully!\n");

        while (1)
        {
            // 从用户输入获取消息
            char buf[1024];
            // printf("请输入消息:");
            fgets(buf, sizeof(buf), stdin);

            // 去除换行符
            buf[strcspn(buf, "\n")] = 0;

            // 检查是否退出
            if (strcmp(buf, "quit") == 0)
            {
                return 0;
            }

            // 发送消息到服务器
            if (send(info->sockfd, buf, strlen(buf), 0) < 0)
            {
                perror("send error");
                break;
            }

            printf("已发送: %s\n", buf);
        }
    }
}

int main()
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0); // 0 表示使用默认协议
    if (sockfd < 0)
    {
        perror("socket error");
        return -1;
    }

    // 创建Server端地址结构体
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(SERVER_PORT);
    addr.sin_addr.s_addr = inet_addr(SERVER_IP);

    // 打包连接数据
    server_info_t *server_info = malloc(sizeof(server_info_t));
    server_info->sockfd = sockfd;
    server_info->addr = addr;

    // 连接服务器
    pthread_t sendTid;
    pthread_create(&sendTid, NULL, send_message, server_info);

    pthread_t revc_tid;
    pthread_create(&revc_tid, NULL, get_message, server_info);

    pthread_join(revc_tid, NULL);
    pthread_join(sendTid, NULL);

    close(sockfd);
    free(server_info);

    return 0;
}
